<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form :inline="true" :model="dataForm">
        <el-form-item label="分类">
          <category-cascader :catelogPath.sync="catelogPath"></category-cascader>
        </el-form-item>
        <el-form-item label="品牌">
          <brand-select style="width:160px"></brand-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number style="width:160px" v-model="dataForm.price.min" :min="0"></el-input-number>-
          <el-input-number style="width:160px" v-model="dataForm.price.max" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="检索">
          <el-input style="width:160px" v-model="dataForm.key" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSkuInfo">查询</el-button>
        </el-form-item>
      </el-form>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;" @expand-change="getSkuDetails" height="67vh">
      <el-table-column type="expand">
        <template slot-scope="scope">
          商品标题：{{scope.row.skuTitle}}
          <br />
          商品副标题：{{scope.row.skuSubtitle}}
          <br />
          商品描述：{{scope.row.skuDesc}}
          <br />
          分类ID：{{scope.row.catalogId}}
          <br />
          SpuID：{{scope.row.spuId}}
          <br />
          品牌ID：{{scope.row.brandId}}
          <br />
        </template>
      </el-table-column>
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <!-- <el-table-column prop="skuId" header-align="center" align="center" label="skuId"></el-table-column> -->
      <el-table-column prop="skuName" header-align="center" align="center" label="名称"></el-table-column>
      <el-table-column prop="skuDefaultImg" header-align="center" align="center" label="默认图片">
        <template slot-scope="scope">
          <img :src="scope.row.skuDefaultImg" style="width:80px;height:80px;" v-if="scope.row.skuDefaultImg" />
          <div v-else>暂无</div>
        </template>
      </el-table-column>
      <el-table-column prop="price" header-align="center" align="center" label="价格(￥)">
        <template slot-scope="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.price" size="mini" @blur="savePrice(scope.row)"
            @keyup.enter.native="savePrice(scope.row)"></el-input>
          <span v-else @click="startEdit(scope.row)" style="cursor:pointer;">
            {{ scope.row.price }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="saleCount" header-align="center" align="center" label="销量"></el-table-column>
      <el-table-column prop="stock" header-align="center" align="center" label="库存"></el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="previewHandle(scope.row.skuId)">预览</el-button>
          <el-button type="text" size="small" @click="commentHandle(scope.row.skuId)">评论</el-button>
          <el-dropdown @command="handleCommand(scope.row,$event)" size="small" split-button type="text">
            更多
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="uploadImages">上传图片</el-dropdown-item>
              <!-- <el-dropdown-item command="seckillSettings">参与秒杀</el-dropdown-item> -->
              <el-dropdown-item command="reductionSettings">满减设置</el-dropdown-item>
              <el-dropdown-item command="discountSettings">折扣设置</el-dropdown-item>
              <el-dropdown-item command="memberPriceSettings">会员价格</el-dropdown-item>
              <el-dropdown-item command="stockSettings">库存管理</el-dropdown-item>
              <el-dropdown-item command="couponSettings">优惠劵</el-dropdown-item>
              <!-- <el-dropdown-item command="updateIinventory">修改库存</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"></el-pagination>

    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <el-dialog :title="form.skuName" :close-on-click-modal="false" :visible.sync="imageUpdateVisible"
      @closed="dialogClose">
      <el-row>
        <el-col :span="24">
          <label style="display:block;float:left">选择图集 或</label>
          <multi-upload style="float:left;margin-left:10px;" :showFile="false" :listType="'text'"
            v-model="uploadImages"></multi-upload>
        </el-col>
        <el-col :span="24">
          <el-divider></el-divider>
        </el-col>
        <el-col :span="24">
          <el-card style="width:220px;float:left;margin-left:15px;margin-top:15px;" :body-style="{ padding: '0px' }"
            v-for="(img,index) in imageList" :key="index">
            <img :src="img.imgUrl" style="width:160px;height:160px" />
            <div style="padding: 14px;">
              <el-row>
                <el-col :span="12">
                  <el-tag>
                    <input type="radio" :checked="img.defaultImg == 1" :name="img.imgUrl"
                      @change="checkDefaultImg(index)" />设为默认
                  </el-tag>
                </el-col>
                <el-col :span="12">
                  <el-button type="danger" size="mini" @click="delImage(img)">删除</el-button>

                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="imageUpdateVisible = false">取消</el-button>
        <el-button type="primary" @click="imageFormSubmit()">确定</el-button>
      </span>
    </el-dialog>


    <el-dialog :title="form.skuName" :close-on-click-modal="false" :visible.sync="settingVisible" @closed="dialogClose">
      <!-- 折扣，满减，会员价 -->
      <el-form :model="settingForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设置折扣" v-if="settingLog == 'discountSettings'">
              <label>满</label>
              <el-input-number style="width:160px" :min="0" controls-position="right"
                v-model="settingForm.fullCount"></el-input-number>
              <label>件</label>

              <label style="margin-left:15px;">打</label>
              <el-input-number style="width:160px" v-model="settingForm.discount" :precision="2" :max="1" :min="0"
                :step="0.01" controls-position="right"></el-input-number>
              <label>折</label>
              <el-checkbox v-model="settingForm.addOther" :true-label="1" :false-label="0">可叠加优惠</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设置满减" v-if="settingLog == 'reductionSettings'">
              <label>满</label>
              <el-input-number style="width:160px" v-model="settingForm.fullPrice" :step="100" :min="0"
                controls-position="right"></el-input-number>
              <label>元</label>
              <label style="margin-left:15px;">减</label>
              <el-input-number style="width:160px" v-model="settingForm.reducePrice" :step="10" :min="0"
                controls-position="right"></el-input-number>
              <label>元</label>
              <el-checkbox v-model="settingForm.addOther" :true-label="1" :false-label="0">可叠加优惠</el-checkbox>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="设置会员价" v-if="settingForm.memberPrice.length>0 && settingLog == 'memberPriceSettings'">
              <br />
              <!--   @change="handlePriceChange(scope,mpidx,$event)" -->
              <el-form-item v-for="(mp,mpidx) in settingForm.memberPrice" :key="mp.id">
                {{mp.memberLevelName}}
                <el-input-number style="width:160px" v-model="settingForm.memberPrice[mpidx].memberPrice" :precision="2"
                  :min="0" controls-position="right"></el-input-number>
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingVisible = false">取消</el-button>
        <el-button type="primary" @click="settingFormSubmit()">确定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
  import CategoryCascader from "../common/category-cascader";
  import BrandSelect from "../common/brand-select";
  import addOrUpdate from "./manager-add-or-update.vue";
  import MultiUpload from "@/components/upload/multiUpload";

  export default {
    data() {
      return {
        catPathSub: null,
        brandIdSub: null,
        dataForm: {
          key: "",
          brandId: 0,
          catelogId: 0,
          price: {
            min: 0,
            max: 0
          }
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        imageUpdateVisible: false,
        settingVisible: false,
        catelogPath: [],
        form: {},
        imageList: [],
        imageLists: [],
        morenImage: "",
        uploadImages: [],
        memberLevels: [],//会员等级列表
        settingLog: '',
        settingForm: {
          fullCount: 0,//满多少件
          discount: 0,//打多少折

          fullPrice: 0,//满多少元
          reducePrice: 0,//减多少元

          addOther: 0,//是否享受优惠 0：否 1：是

          id: null,
          skuId: null,
          memberPrice: [],
        },

      };
    },
    components: {
      CategoryCascader,
      BrandSelect,
      addOrUpdate,
      MultiUpload
    },

    watch: {
      uploadImages(val) {
        let list = val.map(item => {
          return {
            defaultImg: 0,
            imgUrl: item,
            skuId: this.form.skuId,
            id: '',
            imgSort: null
          };
        });

        //扩展每个skus里面的imgs选项
        let imgArr = Array.from(
          new Map(
            this.imageLists.concat(list).map(item => [item.imgUrl, item])
          ).values()
        );

        this.imageList = imgArr; //去重
      }
    },

    activated() {
      this.getDataList();
    },
    methods: {
      getSkuDetails(row, expand) {
        //sku详情查询
        console.log("展开某行...", row, expand);
      },
      //处理更多指令
      handleCommand(row, command) {
        this.form = row;
        if ("stockSettings" == command) {
          this.$router.push({ path: "/sku", query: { skuId: row.skuId } });
        }
        if ("updateIinventory" == command) {

          this.addOrUpdateVisible = true;
          this.$nextTick(() => {
            this.$refs.addOrUpdate.init(row.skuId);
          });
        }

        if ("uploadImages" == command) {
          this.imageUpdateVisible = true;
          this.$http({
            url: this.$http.adornUrl(`/product/skuimages/${this.form.skuId}/images`),
            method: "get",
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.imageList = data.data;
              this.imageLists = data.data;
            }
          });
        }

        if ("reductionSettings" == command) {
          this.settingVisible = true;
          this.settingLog = "reductionSettings";
          //获取满减信息
          this.$http({
            url: this.$http.adornUrl(`/product/skuinfo/getReductionInfo/${this.form.skuId}`),
            method: "get",
          }).then(({ data }) => {
            if (data.data && data.code === 0) {
              let { fullPrice, reducePrice, addOther, id, skuId } = data.data;
              this.settingForm.fullPrice = fullPrice;
              this.settingForm.reducePrice = reducePrice;
              this.settingForm.addOther = addOther;
              this.settingForm.id = id;
              this.settingForm.skuId = skuId;
            }
          });
        }

        if ("discountSettings" == command) {
          this.settingVisible = true;
          this.settingLog = "discountSettings";
          //获取折扣信息
          this.$http({
            url: this.$http.adornUrl(`/product/skuinfo/getDiscountInfo/${this.form.skuId}`),
            method: "get",
          }).then(({ data }) => {
            if (data.data && data.code === 0) {
              console.log(data);
              let { fullCount, discount, addOther, id, skuId } = data.data;
              this.settingForm.id = id;
              this.settingForm.skuId = skuId;
              this.settingForm.fullCount = fullCount;
              this.settingForm.discount = discount;
              this.settingForm.addOther = addOther;
            }
          });
        }


        if ("memberPriceSettings" == command) {
          this.settingVisible = true;
          this.settingLog = "memberPriceSettings";
          //获取会员价信息
          this.$http({
            url: this.$http.adornUrl(`/product/skuinfo/getMemberPriceInfo/${this.form.skuId}`),
            method: "get",
          }).then(({ data }) => {
            if (data.data && data.code === 0) {
              this.settingForm.skuId = this.form.skuId;

              if (this.memberLevels.length > 0) {
                for (let i = 0; i < this.memberLevels.length; i++) {
                  if (this.memberLevels[i].priviledgeMemberPrice == 1) {
                    if (data.data.length > 0) {

                      let condition = data.data.find(mp => mp.memberLevelId == this.memberLevels[i].id);
                      if (condition) {
                        this.settingForm.memberPrice.push({
                          id: condition.id,
                          skuId: condition.skuId,
                          memberLevelId: condition.memberLevelId,
                          memberLevelName: this.memberLevels[i].name,
                          memberPrice: condition.memberPrice || 0
                        });
                      } else {
                        this.settingForm.memberPrice.push({
                          id: null,
                          skuId: this.form.skuId,
                          memberLevelId: this.memberLevels[i].id,
                          memberLevelName: this.memberLevels[i].name,
                          memberPrice: 0
                        })
                      }
                    } else {
                      this.settingForm.memberPrice.push({
                        id: null,
                        skuId: this.form.skuId,
                        memberLevelId: this.memberLevels[i].id,
                        memberLevelName: this.memberLevels[i].name,
                        memberPrice: 0
                      })
                    }
                  }
                }
              }
            }
          });
        }


      },
      // 开始编辑价格
      startEdit(row) {
        this.$set(row, 'editing', true);
        // 保存原始值用于取消时恢复
        this.$set(row, 'originalPrice', row.price);
      },


      // 保存价格
      savePrice(row) {
        // 如果值没有改变，则直接退出编辑模式
        if (row.originalPrice == row.price) {
          this.$set(row, 'editing', false);
          return;
        }

        // 调用接口更新价格
        this.$http({
          url: this.$http.adornUrl(`/product/skuinfo/updatePrice/${row.skuId}?price=${row.price}`),
          method: 'post',
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '价格修改成功',
              type: 'success',
              duration: 1500
            });
            this.$set(row, 'editing', false);
          } else {
            this.$message({
              message: data.msg || '价格修改失败',
              type: 'error',
              duration: 1500
            });
            // 恢复原值
            row.price = row.originalPrice;
            this.$set(row, 'editing', false);
          }
        }).catch(() => {
          this.$message({
            message: '价格修改失败',
            type: 'error',
            duration: 1500
          });
          // 恢复原值
          row.price = row.originalPrice;
          this.$set(row, 'editing', false);
        });
      },


      //保存设置
      settingFormSubmit() {

        let porUrl = '';
        //满减设置
        if (this.settingLog == "reductionSettings") {
          porUrl = `/coupon/skufullreduction/${this.settingForm.id ? 'update' : 'save'}`;
          this.getSettingInfo(porUrl, this.settingForm);
        }

        //折扣设置
        if (this.settingLog == "discountSettings") {
          porUrl = `/coupon/skuladder/${this.settingForm.id ? 'update' : 'save'}`;
          this.getSettingInfo(porUrl, this.settingForm);
        }


        //会员价格设置
        if (this.settingLog == "memberPriceSettings") {



          let memberPrice = this.settingForm.memberPrice
          memberPrice.forEach(mp => {
            let porUrl = `/coupon/memberprice/${mp.id ? 'update' : 'save'}`;


            this.getSettingInfo(porUrl, mp);
          });


        }



      },



      getSettingInfo(porUrl, data) {
        if (data.id == null) {
          data.skuId = this.form.skuId;
        }
        this.$http({
          url: this.$http.adornUrl(porUrl),
          method: "post",
          data: this.$http.adornData(data, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
                this.settingVisible = false;
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      },


      getMemberLevels() {
        this.$http({
          url: this.$http.adornUrl("/member/memberlevel/list"),
          method: "get",
          params: this.$http.adornParams({
            page: 1,
            limit: 500
          })
        })
          .then(({ data }) => {
            this.memberLevels = data.page.list;
          })
          .catch(e => {
            console.log(e);
          });
      },

      searchSkuInfo() {
        this.getDataList();
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true;
        this.$http({
          url: this.$http.adornUrl("/product/skuinfo/list"),
          method: "get",
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            key: this.dataForm.key,
            catelogId: this.dataForm.catelogId,
            brandId: this.dataForm.brandId,
            min: this.dataForm.price.min,
            max: this.dataForm.price.max,
            shopId: sessionStorage.getItem('shopId')
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list;
            this.dataList.forEach(item => {
              // 添加编辑状态字段
              this.$set(item, 'editing', false);
            });


            this.totalPage = data.page.totalCount;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        });
      },

      // 图片上传提交
      imageFormSubmit() {
        console.log("图片列表", this.imageList);

        if (this.imageList.length > 0) {
          const hasDefaultImgZero = this.imageList.some(item => item.defaultImg == 1);
          if (!hasDefaultImgZero) {
            this.$message({
              message: "请设置默认图片！",
              type: "warning",
              duration: 1500,
            });
            return;
          }
          let imagesSaveTo = {
            images: this.imageList,
            skuId: this.form.skuId
          }


          this.$http({
            url: this.$http.adornUrl(
              `/product/skuimages/batchSave`
            ),
            method: "post",
            data: this.$http.adornData(imagesSaveTo, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                  this.imageUpdateVisible = false;
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        } else {
          this.$message({
            message: "请上传图片！",
            type: "warning",
            duration: 1500,
          });
        }
      },

      //设置默认图片
      checkDefaultImg(index) {

        this.imageList[index].defaultImg = 1; //修改标志位;
        //修改其他人的标志位
        this.imageList.forEach((item, idx) => {
          if (idx != index) {
            this.imageList[idx].defaultImg = 0;
          }
        });

        console.log("默认图片", this.imageList);

      },

      //删除图片
      delImage(img) {
        this.imageList = this.imageList.filter(item => item.imgUrl !== img.imgUrl);
        this.imageLists = this.imageLists.filter(item => item.imgUrl !== img.imgUrl);
      },

      //dialogClose
      dialogClose() {
        this.form = {};
        this.imageList = [];
        this.uploadImages = [];
        this.settingForm = {
          fullCount: 0,//满多少件
          discount: 0,//打多少折

          fullPrice: 0,//满多少元
          reducePrice: 0,//减多少元

          addOther: 0,//是否享受优惠 0：否 1：是

          id: null,
          skuId: null,
          memberPrice: [],
        };
      },



      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getDataList();
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getDataList();
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val;
      }
    },
    mounted() {
      this.catPathSub = PubSub.subscribe("catPath", (msg, val) => {
        this.dataForm.catelogId = val[val.length - 1];
      });
      this.brandIdSub = PubSub.subscribe("brandId", (msg, val) => {
        this.dataForm.brandId = val;
      });
      this.getMemberLevels();
    },
    beforeDestroy() {
      PubSub.unsubscribe(this.catPathSub);
      PubSub.unsubscribe(this.brandIdSub);
    } //生命周期 - 销毁之前
  };
</script>